package com.huluobo.a2107jetpackkotlindemo.room

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.huluobo.a2107jetpackkotlindemo.MyApp
import com.huluobo.a2107jetpackkotlindemo.R
import com.huluobo.a2107jetpackkotlindemo.databinding.ActivityRoomBinding

/**
 *  by lazy 是通过懒加载实现的创建对象, LazyThreadSafetyMode.SYNCHRONIZED 同步锁,可以控制线程安全
 */
class RoomActivity : AppCompatActivity() {
    private lateinit var activityRoomBinding: ActivityRoomBinding

    companion object {
        val accountDatabase by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            Room.databaseBuilder(
                MyApp.instance,
                AccountDatabase::class.java,
                "account.db"
            ).allowMainThreadQueries()
                .addMigrations(MIGRATION_3_4)
//                .fallbackToDestructiveMigration()//破坏性重建数据库,会丢失所有数据
                .build()
        }

        private val MIGRATION_3_4 = object : Migration(3, 4) {
            override fun migrate(database: SupportSQLiteDatabase) {
                //ALTER 提醒,找到
                //TABLE 表名
                //ADD COLUMN 添加一个字段
                //TEXT 文本
                //NOT NULL DEFAULT 非空,默认值是一个单引号''
                database.execSQL("ALTER TABLE Account ADD COLUMN _loginAge TEXT NOT NULL DEFAULT ''")
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityRoomBinding = ActivityRoomBinding.inflate(layoutInflater)
        setContentView(activityRoomBinding.root)

        //保存
        activityRoomBinding.btnInsert.setOnClickListener {

            val account =
                accountDatabase.accountDao.findAccountByLoginAccount(activityRoomBinding.edLoginAccount.text.toString())
            account?.let {
                Log.i("TagA", "账号已存在")
                //如果账号存在,密码也相同,不做任何操作,如果不同,则更新密码
                if (it.loginPassword != activityRoomBinding.edLoginPassword.text.toString()) {
                    it.loginPassword = activityRoomBinding.edLoginPassword.text.toString()
                    accountDatabase.accountDao.updateAccountBean(it)
                }
            } ?: let {
                Log.i("TagA", "账号存不在")
                val accountBean = AccountBean(
                    loginAccount = activityRoomBinding.edLoginAccount.text.toString(),
                    loginPassword = activityRoomBinding.edLoginPassword.text.toString(),
                    loginIPAddress = "",
                    sex = "",
                    loginAge = ""
                )
                accountDatabase.accountDao.insertAccount(accountBean)
            }
        }

        //查询
        activityRoomBinding.btnQuery.setOnClickListener {
            val list = accountDatabase.accountDao.queryAccountList()

            list?.let {
                activityRoomBinding.tvResult.text = ""
                for (i in it.indices) {
                    activityRoomBinding.tvResult.append("账号:${it[i].loginAccount}")
                    activityRoomBinding.tvResult.append("密码:${it[i].loginPassword}")
                }
            }
        }

        //删除
        activityRoomBinding.btnDelete.setOnClickListener {
            val list = accountDatabase.accountDao.queryAccountList()
            list?.let {
                for (i in it.indices) {
                    if (it[i].loginAccount == activityRoomBinding.edLoginAccount.text.toString()) {
                        accountDatabase.accountDao.deleteAccountBean(it[i])
                    }
                }
            }
        }

    }

}